//
//  LoginViewController.m
//  seer
//
//  Created by Lin Eidan on 14-5-28.
//  Copyright (c) 2014年 haomee. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "config.h"
#import "Header.h"
#import <Frontia/Frontia.h>

@interface LoginViewController ()

@property (strong, nonatomic) IBOutlet UIView *navBarView;

@property (strong, nonatomic) IBOutlet UITextField *phoneField;
@property (strong, nonatomic) IBOutlet UITextField *passwordField;


@property (strong, nonatomic) IBOutlet UILabel *otherLoginLabel;
@property (strong, nonatomic) IBOutlet UIButton *qqBtn;
@property (strong, nonatomic) IBOutlet UIButton *sinaBtn;

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization 
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self drawNavTopContentView:self.navBarView];
    
    if ([kHandle sharedInstance].isShowTrueView) {
        self.otherLoginLabel.hidden = NO;
        self.qqBtn.hidden = NO;
        self.sinaBtn.hidden = NO;
    }else{
        self.otherLoginLabel.hidden = YES;
        self.qqBtn.hidden = YES;
        self.sinaBtn.hidden = YES;
    }
    
}

- (IBAction)thirdLogin:(id)sender {
    UIButton *button = (UIButton *)sender;
    FrontiaAuthorization * authorization = [Frontia getAuthorization];
    
    NSString *platformType = nil;
    NSString *type = nil;
    switch (button.tag){
        case 1:
            platformType = FRONTIA_SOCIAL_PLATFORM_QQ;
            type = BindQQPfIndex;
            break;
        case 2:
            platformType = FRONTIA_SOCIAL_PLATFORM_SINAWEIBO;
            type = BindSinaPfIndex;
            break;
        default:
            break;
    }
    
    FrontiaAuthorizationCancelCallback onCancel = ^(){
        [kApp hideWaitView];
        NSLog(@"OnCancel: authorization is cancelled");
    };
    
    FrontiaAuthorizationFailureCallback onFailure = ^(int errorCode, NSString *errorMessage){
        [kApp hideWaitView];
        [PopTips tipsAtTop:self.view Msg:NotifyThirdAuthorizeFaild];
    };
    
    FrontiaAuthorizationResultCallback onResult = ^(FrontiaUser *result){
        [Frontia setCurrentAccount:result];
//        NSLog(@"%@ %@ %@ %@",  result.mediaUid,result.accountId,result.accountName,result.accessToken);
        NSString *url = [NSString stringWithFormat:@"%@pfLogin",API_BASE];
        NSDictionary *dic = @{@"pf_type": type ,@"pf_id":result.mediaUid,@"ak":[Common md5:[NSString stringWithFormat:@"%@%@",type,result.mediaUid]]};
        NSLog(@"dict = %@",dic);
        [[AFGetData sharedInstance] startPost:url andInfo:dic andDataBodyBlock:^(id<AFMultipartFormData> formData) {
            
        } andRequestCompletion:^(id responseObj, BOOL isSuccess) {
            [kApp hideWaitView];
            if (isSuccess) {
                int flag = [[responseObj objectForKey:@"flag"] intValue];
                NSDictionary *user = [responseObj objectForKey:@"user"];
                
                UserObj *obj = [UserObj sharedInstance];
                obj.thridPlatform = type;
                obj.thridPlatformID = result.mediaUid;
                obj.thridAccountName = result.accountName;
                
                if (0 == flag) {  //需要绑定手机
                    RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
                    registerVC.isFromThirdLogin = YES;
                    [self.navigationController pushViewController:registerVC animated:YES];
                    
                }else if (1 == flag){
                    
                    obj.isLogin = YES;
                    obj.uid = [user objectForKey:@"uid"];
                    obj.accessKey = [user objectForKey:@"accesskey"];
                    
                    if ([obj.thridPlatform isEqualToString:BindQQPfIndex]) { //qq
                        obj.qqNickName = obj.thridAccountName;
                    }else{
                        obj.sinaNickName = obj.thridAccountName;
                    }
                    
                    [obj saveUserToLocal];
                    [self.navigationController popToViewController:kApp.meHomeVC animated:YES];
                    [PopTips tipsAtTop:kApp.rootNav.view Msg:NotifyLoginSuccess];
                }else{
                    [PopTips tipsAtTop:kApp.rootNav.view Msg:NotifyLoginFaild];
                }
                
            }else{
                [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
            }
        }];
        
    };
    [kApp displayWaitViewWithAllMaskView:NO];
    [authorization authorizeWithPlatform:platformType supportedInterfaceOrientations:UIInterfaceOrientationMaskPortrait isStatusBarHidden:NO cancelListener:onCancel failureListener:onFailure resultListener:onResult];
}


#pragma -mark xib click
- (IBAction)phoneLogin:(id)sender {
    if (![Common checkPhoneLegal:self.phoneField.text]) {
        [PopTips tipsAtTop:self.view Msg:NotifyInvalidPhone];
        return;
    }
    if (self.passwordField.text.length < 6) {
        [PopTips tipsAtTop:self.view Msg:NotifyInvalidPW];
        return;
    }
    NSString *pw = [Common md5:self.passwordField.text];
    NSString *url = [NSString stringWithFormat:@"%@phoneLogin&pas=%@&mobile=%@",API_BASE,pw,self.phoneField.text];
    
    [kApp displayWaitViewWithAllMaskView:NO];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        [kApp hideWaitView];
        if (isSuccess) {
            NSDictionary *dic = responseObj;
            int flag = [[dic objectForKey:@"flag"] intValue];
            if (1 == flag) {
                NSDictionary *user = [dic objectForKey:@"user"];
                [UserObj sharedInstance].uid = [user objectForKey:@"uid"];
                [UserObj sharedInstance].accessKey = [user objectForKey:@"accesskey"];
                [UserObj sharedInstance].isLogin = YES;
                [[UserObj sharedInstance] saveUserToLocal];
                [PopTips tipsAtTop:kApp.rootNav.view Msg:NotifyLoginSuccess];
                
                for (UIViewController *VC in self.navigationController.viewControllers) {
                    if ([VC isKindOfClass:[MeHomeViewController class]]) {
                        [self.navigationController popToViewController:(UIViewController *)VC animated:YES];
                    }
                }
            }else{
                NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError
                                                                  title:NotifyTitleWarning
                                                                message:NotifyLoginFaild
                                                               delegate:nil];
                [alert show];
            }
        }else{
            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
        }
        
    }];

    
}

- (IBAction)goRegister:(id)sender {
    RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    [self.navigationController pushViewController:registerVC animated:YES];
}

- (IBAction)goForgetPassword:(id)sender {
    RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    registerVC.isFromForgetPassword = YES;
    [self.navigationController pushViewController:registerVC animated:YES];
}

- (IBAction)goBack:(id)sender {
    [kApp hideWaitView];
    [[AFGetData sharedInstance] removeAllGetAndPostRequest];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	[self.view.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
		if ([obj isKindOfClass:[UITextField class]]) {
			[obj resignFirstResponder];
		}
	}];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
